import router,{resetRouter, asyncRouterList} from '@/router/index';
// import Layout from "@/layouts";


// 引入所有views下.vue文件
const modules = import.meta.glob("../../pages/**/**.vue");


function  createCustomComponent (name, component) {
  return {
    name,
    data () {
      return { component: null }
    },
    async created () {
      if (component instanceof Promise) {
        try {
          const module = await component
          this.component = module?.default
        } catch (error) {
          console.error(`can not resolve component ${name}, error:`, error)
        }

        return
      }
      this.component = component
    },
    render (h) {
      return this.component ? h(this.component) : null
    },
  }
}

function filterPermissionsRouters(services) {
  const res = [];
  const res2 = []
  const asyncMenus = [];
  services.forEach(service => {
    if (service.sysMenus.length<=0){ // 没有绑定菜单则表示没有权限默认添加一级权限
      res2.push({
        path: service.serviceCode,
        redirect: "",
        meta: {
          hidden: undefined,
          icon: undefined,
          title: service.serviceName,
          isOrNot: false,
          isAlive: true
        },
        component: undefined,
        children: [],
      })
      return false;
    }
    if(service.isOrNot && service.isOrNot===true){
      asyncMenus.push(service.sysMenus);
    }
  });
  asyncMenus.forEach((asyncRoutes,index) => {
    asyncRoutes.forEach((route) => {
      const newRoute = {
        path: "",
        redirect: "",
        meta: {
          hidden: undefined,
          icon: undefined,
          title: undefined,
          isOrNot: undefined,
          isAlive: true
        },
        component: undefined,
        children: [],
      }
      // 一级菜单
      newRoute.path = `/${route.path}`;
      newRoute.component = () => import(`@/layouts`);
      newRoute.meta.isOrNot = true;
      if (route.visible === "1") {
        newRoute.meta.hidden = true;
      }
      newRoute.meta.title = route.menuName;
      newRoute.meta.icon = route.icon;
      if (route.children?.length > 0) {
        // newRoute.redirect = `${newRoute.path}/${route.children[0].path}`;
        newRoute.redirect = `/${route.children[0].path}` // 跳转菜单
        if(route.children[0].children?.length>0){
          newRoute.redirect = `/${route.children[0].children[0].path}` // 跳转目录菜单
        }
      } else {
        delete newRoute.redirect;
      }
      // 二级菜单
      const children = [];
      route.children?.forEach((childRoute) => {
        const newChildRoute = {
          path: "",
          redirect: "",
          meta: {
            hidden: undefined,
            icon: undefined,
            title: undefined,
            isAlive: true
          },
          component: undefined,
          children: [],
        }
        newChildRoute.path = childRoute.path.replace(`${route.path}/`,"");
        newChildRoute.meta.title = childRoute.menuName;
        newChildRoute.meta.icon = childRoute.icon;
        if (childRoute.visible === "1") {
          newChildRoute.meta.hidden = true;
        }
        if (childRoute.children?.length > 0) {
          newChildRoute.component = () => import(`@/layouts/blank.vue`);
          // newChildRoute.redirect = `${newRoute.redirect}/${childRoute.children[0].path}`;
          newChildRoute.redirect = `/${childRoute.children[0].path}`;
        } else {
          if (childRoute.component === 'blank'){
            newChildRoute.component = () => import(`@/layouts/blank.vue`);
          }else {
            newChildRoute.component = modules[`../../pages/${childRoute.component}.vue`]
          }

          delete newChildRoute.redirect;
        }
        // 三级菜单
        const lastChildren = [];
        childRoute.children?.forEach((lastChildRoute) => {
          const newLastChildRoute = {
            path: "",
            redirect: "",
            meta: {
              hidden: undefined,
              icon: undefined,
              title: undefined,
              isAlive: lastChildRoute.isCache === '0',
              activeMenu: '',
              query: lastChildRoute.query,
            },
            component: undefined,
            children: [],
            name: lastChildRoute.path.replaceAll("/","-")
          }
          newLastChildRoute.path = lastChildRoute.path.replace(`${childRoute.path}/`,"");
          // console.log(lastChildRoute.path,lastChildRoute.path.replace(`${childRoute.path}/`,""),"11111")
          newLastChildRoute.meta.title = lastChildRoute.menuName;
          newLastChildRoute.meta.icon = lastChildRoute.icon;
          if (lastChildRoute.visible === "1") {
            newLastChildRoute.meta.hidden = true;
          }
          if(lastChildRoute.activeMenu){
            newLastChildRoute.meta.activeMenu =  `/${lastChildRoute.activeMenu}`;
          }
          // 针对于未开发页面
          if(newLastChildRoute.component === 'blank'){
            newLastChildRoute.component = () => import(`@/pages/blank.vue`);
          }else {
            newLastChildRoute.component = createCustomComponent(lastChildRoute.path.replaceAll("/","-"),modules[`../../pages/${lastChildRoute.component}.vue`])
          }
          delete newLastChildRoute.redirect;
          lastChildren.push(newLastChildRoute);
        })
        if (lastChildren.length > 0) {
          newChildRoute.children = lastChildren;
        }
        children.push(newChildRoute);
      })
      if (children.length > 0) {
        newRoute.children = children;
      }
      res.push(newRoute);
    });

  });
  return res.concat(res2);
}


const state = {
  whiteListRouters: ['/login', '/auth-redirect', '/bind', '/register'],
  routers: [],
  currentSystemRouters: []
};

const mutations = {
  setRouters: (state, routers) => {
    state.routers = routers;
  },
  setCurrentSystemRouters: (state, routers) => {
    state.currentSystemRouters = routers;
  },
};

const getters = {
  routers: (state) => state.routers,
  whiteListRouters: (state) => state.whiteListRouters,
};

const actions = {
  async initRoutes({commit}, {permissions, services}) {
    // let accessedRouters;
    // special token
    // if (permissions.includes("*:*:*")) {
    //   accessedRouters = asyncRouterList;
    // } else {
    //   accessedRouters = filterPermissionsRouters(services);
    // }
    const accessedRouters = filterPermissionsRouters(services);
    commit('setRouters', accessedRouters);
    resetRouter();
    accessedRouters.forEach(route =>{
      router.addRoute(route);
    })
    if(accessedRouters.length<=0){
      router.addRoute({
        path:"*",
        component: () => import('@/pages/common/404.vue'),
      });
    }else {
      router.addRoute({
        path: '/',
        redirect: accessedRouters[0].path
      })
      router.addRoute({
        path:"*",
        component: () => import('@/pages/common/404.vue'),
      });
      // router.addRoute({
      //   ...accessedRouters[0],
      //   path:"*",
      // });
    }
  },
  async restore({commit}) {
    // remove routers
    resetRouter();
    commit('setRouters', []);
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
};
